import datetime
import requests
import json
import sqlite3
import time
from config import WEATHER_API_KEY

# 主菜单显示
class MentalHealthSystem:
    def __init__(self):
        self.current_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
        self.conn = sqlite3.connect('user_data.db')
        self.create_table()
        self.weather_info = self.get_weather(WEATHER_API_KEY)
        
    def get_weather(self, api_key, city="Changchun"):
        base_url = "http://api.openweathermap.org/data/2.5/weather"
        
        params = {
            "q": city,
            "appid": api_key,
            "units": "metric"
        }

        try:
            response = requests.get(base_url, params=params)
            data = response.json()
            
            if response.status_code == 200:
                weather_translation = {
                    "clear sky": "晴天",
                    "few clouds": "少云",
                    "scattered clouds": "散云",
                    "broken clouds": "多云",
                    "overcast clouds": "阴天",
                    "light rain": "小雨",
                    "moderate rain": "中雨",
                    "heavy rain": "大雨",
                    "thunderstorm": "雷雨",
                    "snow": "雪",
                    "mist": "薄雾"
                }
                weather_description = data["weather"][0]["description"]
                weather_info = {
                    "城市": data["name"],
                    "温度": data["main"]["temp"],
                    "体感温度": data["main"]["feels_like"],
                    "天气状况": weather_translation.get(weather_description, weather_description),
                    "湿度": data["main"]["humidity"],
                    "风速": data["wind"]["speed"],
                    "更新时间": time.strftime("%Y-%m-%d %H:%M:%S", 
                                      time.localtime(data["dt"]))
                }
                return weather_info
            else:
                print(f"错误: {data['message']}")
                return None
                
        except requests.exceptions.RequestException as e:
            print(f"网络连接失败: {str(e)}")
            print("请检查您的网络连接后重试")
            return None
        except json.JSONDecodeError:
            print("天气API响应解析失败，可能是API密钥无效")
            print(f"当前使用的API密钥: {api_key}")
            return None
        except Exception as e:
            print(f"获取天气失败: {str(e)}")
            return None




    def create_table(self):
        cursor = self.conn.cursor()
        cursor.execute('''CREATE TABLE IF NOT EXISTS users
                        (id INTEGER PRIMARY KEY AUTOINCREMENT,
                        name TEXT,
                        gender TEXT,
                        age INTEGER,
                        contact TEXT,
                        test_time DATETIME,
                        score INTEGER,
                        health_index TEXT,
                        guardian_name TEXT,
                        guardian_gender TEXT,
                        guardian_contact TEXT,
                        guardian_relation TEXT,
                        guardian_status INTEGER DEFAULT 0)''')
        self.conn.commit()
        
        # 确保所有列都存在
        cursor.execute('PRAGMA table_info(users)')
        columns = [col[1] for col in cursor.fetchall()]
        
        if 'guardian_name' not in columns:
            cursor.execute('ALTER TABLE users ADD COLUMN guardian_name TEXT')
        if 'guardian_gender' not in columns:
            cursor.execute('ALTER TABLE users ADD COLUMN guardian_gender TEXT')
        if 'guardian_contact' not in columns:
            cursor.execute('ALTER TABLE users ADD COLUMN guardian_contact TEXT')
        if 'guardian_relation' not in columns:
            cursor.execute('ALTER TABLE users ADD COLUMN guardian_relation TEXT')
        if 'guardian_status' not in columns:
            cursor.execute('ALTER TABLE users ADD COLUMN guardian_status INTEGER DEFAULT 0')
        
        self.conn.commit()

    def show_main_menu(self):
        try:
            print(f"\n当前日期：{self.current_date}")
            if hasattr(self, 'weather_info') and self.weather_info:
                print("\n=== 当前天气信息 ===")
                print(f"城市: {self.weather_info['城市']}")
                print(f"天气: {self.weather_info['天气状况']}")
                print(f"温度: {self.weather_info['温度']}°C (体感 {self.weather_info['体感温度']}°C)")
                print(f"湿度: {self.weather_info['湿度']}%")
                print(f"风速: {self.weather_info['风速']} m/s")
                print(f"更新时间: {self.weather_info['更新时间']}")
                print("==================")
            print("\n“萤火护心计划”大学生心理暗夜导航工程")
            print("1. 心理健康测评")
            print("2. 人工智能语言分析")
            print("3. 查看用户信息表")
            print("4. 智能AI对话")
            print("5. 守护功能设置")
            print("0. 退出系统\n")
        except Exception as e:
            print(f"显示主菜单时发生错误: {str(e)}")

    def show_guardian_settings(self):
        cursor = self.conn.cursor()
        cursor.execute('SELECT guardian_name, guardian_gender, guardian_contact, guardian_relation, guardian_status FROM users ORDER BY id DESC LIMIT 1')
        guardian = cursor.fetchone()
        
        if guardian and any(guardian[:4]):
            print("\n当前守护人信息：")
            print(f"姓名：{guardian[0] or '未设置'}")
            print(f"性别：{guardian[1] or '未设置'}")
            print(f"联系电话：{guardian[2] or '未设置'}")
            print(f"与您的关系：{guardian[3] or '未设置'}")
            print(f"守护状态：{'已激活' if guardian[4] else '未激活'}")
        else:
            print("\n尚未设置守护人")
            
        print("\n1. 设置/修改守护人信息")
        print("2. 激活/取消守护功能")
        print("3. 发送测评结果给监护人")
        print("4. 返回主菜单")
        choice = input("请选择操作：")
        
        if choice == '1':
            name = input("请输入守护人姓名：")
            gender = input("请输入守护人性别(男/女)：")
            contact = input("请输入守护人联系电话：")
            relation = input("请输入与您的关系：")
            
            # 先检查是否有记录
            cursor.execute('SELECT id FROM users ORDER BY id DESC LIMIT 1')
            last_id = cursor.fetchone()
            
            if last_id:
                cursor.execute('''UPDATE users SET 
                                guardian_name=?, guardian_gender=?, 
                                guardian_contact=?, guardian_relation=?
                                WHERE id = ?''',
                             (name, gender, contact, relation, last_id[0]))
                self.conn.commit()
                print("守护人信息已更新")
            else:
                print("没有找到用户记录，请先完成心理健康测评")
        elif choice == '2':
            cursor.execute('SELECT id, guardian_status FROM users ORDER BY id DESC LIMIT 1')
            record = cursor.fetchone()
            if record:
                new_status = 0 if record[1] else 1
                cursor.execute('UPDATE users SET guardian_status=? WHERE id=?', (new_status, record[0]))
                self.conn.commit()
                print(f"守护功能已{'激活' if new_status else '取消'}")
            else:
                print("没有找到用户记录，请先完成心理健康测评")
        elif choice == '3':
            cursor.execute('SELECT name, score, health_index FROM users ORDER BY id DESC LIMIT 1')
            record = cursor.fetchone()
            if record:
                try:
                    import yagmail
                    yag = yagmail.SMTP(
                        host='smtp.qq.com',
                        user='3031176616@qq.com',
                        password='dkpfzgzopeftddie',
                        smtp_ssl=True
                    )
                    
                    subject = '心理健康测评结果SOS' if int(record[1]) < 40 else '心理健康测评结果'
                    content = f"心理健康测评结果\n姓名: {record[0]}\n得分: {record[1]}\n健康状况: {record[2]}"
                    
                    yag.send(
                        to='3031176616@qq.com',
                        subject=subject,
                        contents=content
                    )
                    print("测评结果已发送给监护人")
                except Exception as e:
                    print(f"发送邮件失败: {str(e)}")
            else:
                print("没有找到用户记录，请先完成心理健康测评")
            
    def run(self):
        while True:
            self.show_main_menu()
            choice = input("请选择功能编号：")
            if choice == '1':
                self.mental_health_test()
        
    def mental_health_test(self):
        from mental_test import MentalTest
        test = MentalTest()
        test = MentalTest()
        user_info = test.get_user_info()
        selected_test = test.select_test(user_info['age'])
        score = test.conduct_test(selected_test)
        test.evaluate_result(selected_test, score)
        test.save_result(self.conn, user_info, selected_test['title'], score)
    
    def text_analysis(self):
        from nlp_analysis import TextAnalyzer
        text = input('\n请输入需要分析的文本：')
        analyzer = TextAnalyzer()
        result = analyzer.analyze_emotion(text)
        analyzer.generate_report(result)
    
    def show_user_records(self):
        cursor = self.conn.cursor()
        cursor.execute('SELECT * FROM users ORDER BY test_time DESC LIMIT 10')
        records = cursor.fetchall()
        print('\n最近10条测评记录：')
        for row in records:
            health_status = "健康" if int(row[6]) >= 60 else "不健康"
            guardian_status = "★" if int(row[6]) < 40 else ""
            guardian_set = "(已守护)" if row[12] is not None and int(row[12]) == 1 else ""
            print(f'{row[0]}. {guardian_status} {row[1]}（{row[2]}）得分：{row[6]}（{health_status}）情绪：{row[7]} {guardian_set} 时间：{row[5]}')
        
        choice = input('\n输入记录ID删除或0返回：')
        if choice != '0':
            try:
                cursor.execute('DELETE FROM users WHERE id = ?', (choice,))
                self.conn.commit()
                print('记录已删除')
            except:
                print('删除失败')
    
    def ai_chat(self):
        from ai_chat import DeepSeekChat
        chat = DeepSeekChat()
        chat.chat_loop()
    
    def show_guardian_settings(self):
        cursor = self.conn.cursor()
        cursor.execute('SELECT guardian_name, guardian_gender, guardian_contact, guardian_relation, guardian_status FROM users ORDER BY id DESC LIMIT 1')
        guardian = cursor.fetchone()
        
        if guardian and any(guardian[:4]):
            print("\n当前守护人信息：")
            print(f"姓名：{guardian[0] or '未设置'}")
            print(f"性别：{guardian[1] or '未设置'}")
            print(f"联系电话：{guardian[2] or '未设置'}")
            print(f"与您的关系：{guardian[3] or '未设置'}")
            print(f"守护状态：{'已激活' if guardian[4] else '未激活'}")
        else:
            print("\n尚未设置守护人")
            
        print("\n1. 设置/修改守护人信息")
        print("2. 激活/取消守护功能")
        print("3. 发送测评结果给监护人")
        print("4. 返回主菜单")
        choice = input("请选择操作：")
        
        if choice == '1':
            name = input("请输入守护人姓名：")
            gender = input("请输入守护人性别(男/女)：")
            contact = input("请输入守护人联系电话：")
            relation = input("请输入与您的关系：")
            
            # 先检查是否有记录
            cursor.execute('SELECT id FROM users ORDER BY id DESC LIMIT 1')
            last_id = cursor.fetchone()
            
            if last_id:
                cursor.execute('''UPDATE users SET 
                                guardian_name=?, guardian_gender=?, 
                                guardian_contact=?, guardian_relation=?
                                WHERE id = ?''',
                             (name, gender, contact, relation, last_id[0]))
                self.conn.commit()
                print("守护人信息已更新")
            else:
                print("没有找到用户记录，请先完成心理健康测评")
        elif choice == '2':
            cursor.execute('SELECT id, guardian_status FROM users ORDER BY id DESC LIMIT 1')
            record = cursor.fetchone()
            if record:
                new_status = 0 if record[1] else 1
                cursor.execute('UPDATE users SET guardian_status=? WHERE id=?', (new_status, record[0]))
                self.conn.commit()
                print(f"守护功能已{'激活' if new_status else '取消'}")
            else:
                print("没有找到用户记录，请先完成心理健康测评")
        elif choice == '3':
            cursor.execute('SELECT name, score, health_index FROM users ORDER BY id DESC LIMIT 1')
            record = cursor.fetchone()
            if record:
                try:
                    import yagmail
                    yag = yagmail.SMTP(
                        host='smtp.qq.com',
                        user='3031176616@qq.com',
                        password='dkpfzgzopeftddie',
                        smtp_ssl=True
                    )
                    
                    subject = '心理健康测评结果SOS' if int(record[1]) < 40 else '心理健康测评结果'
                    content = f"心理健康测评结果\n姓名: {record[0]}\n得分: {record[1]}\n健康状况: {record[2]}"
                    
                    yag.send(
                        to='3031176616@qq.com',
                        subject=subject,
                        contents=content
                    )
                    print("测评结果已发送给监护人")
                except Exception as e:
                    print(f"发送邮件失败: {str(e)}")
            else:
                print("没有找到用户记录，请先完成心理健康测评")
            
    def run(self):
        while True:
            self.show_main_menu()
            choice = input("请选择功能编号：")
            if choice == '1':
                self.mental_health_test()
            elif choice == '2':
                self.text_analysis()
            elif choice == '3':
                self.show_user_records()
            elif choice == '4':
                self.ai_chat()
            elif choice == '5':
                self.show_guardian_settings()
            elif choice == '0':
                print("感谢使用，再见！")
                self.conn.close()
                break
            else:
                print("输入无效，请重新选择！")



if __name__ == "__main__":
    system = MentalHealthSystem()
    system.run()